//
//  BuildinglayoutViewController.m
//  Utils
//
//  Created by enghou on 2018/7/2.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "BuildinglayoutViewController.h"
#import "NetWorkerManager.h"
#import "BuildingLayoutItemModel.h"
#import "BuildingLayoutCell.h"
#import "CollectionHeader.h"
#import "RealHouseListViewController.h"
#import "RealHouseListVC.h"
@interface BuildinglayoutViewController ()

@end

@implementation BuildinglayoutViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    if (self.needLayout) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"创建布局" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = @"请输入层数";
            textField.keyboardType = UIKeyboardTypeNumberPad;
        }];
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = @"请输入户数";
            textField.keyboardType = UIKeyboardTypeNumberPad;
        }];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"创建" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (alert.textFields[0].text.length == 0) {
                [self alertSome:@"请输入层数!"];
                return ;
            }
            if (alert.textFields[1].text.length == 0) {
                [self alertSome:@"请输入户数"];
            }
            
            [[NetWorkerManager sharedInstance]postWithPath:@"/mobile/comprehensiveGovernance/builddatas/addBuildLayout.action" parameter:@{@"builddatas.id":self.ids,@"layoutRow":alert.textFields[0].text,@"layoutColumn":alert.textFields[1].text} completeBlock:^(NSDictionary *source) {
                [self endLoading];
                BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
                if (model.success) {
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"RefreshLst" object:nil];
                    [self getLayout];
                }else{
                    [self alertSome:model.msg];
                }
            } failBlock:^(NSInteger code) {
                [self alertSome:kNetWorkFail];
            }];
        }];
        [alert addAction:action1];
        [self presentVC:alert];
    }else{
        [self getLayout];
    }
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"BuildingLayoutCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:reuseIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:@"CollectionHeader" bundle:[NSBundle mainBundle]] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionHeader"];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refresh:) name:@"RefreshLayout" object:nil];
}

-(void)refresh:(NSNotification *)not{
    for (NSArray *array in self.source) {
        [array enumerateObjectsUsingBlock:^(BuildingLayoutItemModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isEqual:not.object]) {
                obj.isHouse = YES;
            }
        }];
    }
    [self.collectionView reloadData];
}

-(void)getLayout{
    [self beginLoading];
    [[NetWorkerManager sharedInstance]postWithPath:@"/mobile/comprehensiveGovernance/builddatas/getBuildLayout.action" parameter:@{@"id":self.ids} completeBlock:^(NSDictionary *source) {
        [self endLoading];
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:[BuildingLayoutItemModel class]];
        if (model.success) {
            NSDictionary *data = source[@"data"];
            NSArray *layout = data[@"buildLayout"];
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *element in layout) {
                BuildingLayoutItemModel *item = [[BuildingLayoutItemModel alloc]initWithSource:element];
                [array addObject:item];
            }
            NSMutableArray *sectionedArr = [NSMutableArray array];
            [array enumerateObjectsUsingBlock:^(BuildingLayoutItemModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSInteger row = obj.layoutRow;
                if (sectionedArr.count < row) {
                    NSMutableArray *tmp = [NSMutableArray array];
                    [sectionedArr addObject:tmp];
                }
                NSMutableArray *ar = sectionedArr[row - 1];
                [ar addObject:obj];
            }];
            self.source = sectionedArr;
            [self.collectionView reloadData];
        }else{
            [self alertSome:model.msg];
        }
    } failBlock:^(NSInteger code) {
        [self alertSome:kNetWorkFail];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.source.count;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSArray *array = self.source[section];
    return array.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BuildingLayoutCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setModel:)]) {
        [cell performSelector:@selector(setModel:) withObject:self.source[indexPath.section][indexPath.row]];
    }
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    CollectionHeader *reusableview = nil;
    
    if (kind == UICollectionElementKindSectionHeader)
    {
        CollectionHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionHeader" forIndexPath:indexPath];
        reusableview = headerView;
    }
    
    reusableview.titleLbl.text = [NSString stringWithFormat:@"第%li层",indexPath.section + 1];
    
    return reusableview;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    RealHouseListVC *real = [[RealHouseListVC alloc]init];
    real.title = @"实有房屋";
    real.hidesBottomBarWhenPushed = YES;
    BuildingLayoutItemModel *model = self.source[indexPath.section][indexPath.row];
    real.model = model;
    [self push:real];
}

#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

@end
